// -*- coding: utf-8 -*-
/*
 *   Author: William Wong <librehat@outlook.com>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU Library General Public License as
 *   published by the Free Software Foundation; either version 3 or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details
 *
 *   You should have received a copy of the GNU Library General Public
 *   License along with this program; if not, write to the
 *   Free Software Foundation, Inc.,
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

import QtQuick 1.1
import org.kde.plasma.components 0.1 as PlasmaComponents
import org.kde.plasma.extras 0.1 as PlasmaExtras

Item {
    id: mainWindow
    property int minimumWidth: 200;
    property int minimumHeight: 200;

    //Properties below are specified for the sake of conveniece
    property bool m_customFont;
    property string m_fontFamily;//specify font family
    property string m_city;//fixed-line area code, Chinese and pinyin are accepted.
    property string m_cityname;//get exact cityname from remote server
    property int m_interval;//autoupdate interval, unit: hour
    property string error;//error string
    property string m_stations;//store each station
    property string m_aqis;//store each aqi
    property string m_qualitys;//store each quality
    property string m_ppollutants;//store each primary pollutant
    property string m_pm2_5s;//store each pm2.5
    property string m_pm10s;//store each pm10
    property string m_cos;//store each co
    property string m_no2s;//store each no2
    property string m_so2s;//store each so2
    property string m_o38hs;//store each o3/8h
    property string m_avgAQI;//average aqi
    property string m_avgQuality;//average air quality
    property string m_avgPollutant;//primary pollutant on average, it may be null
    property string m_avgpm25;//average pm2.5 index
    property string m_timePoint;//data source updated time
    property string m_rankNum;
    property string m_rankCities;
    property string m_rankAQIs;
    property string m_rankQuality;
    property string m_rankLevel;
    property string m_rankPPollutants;
    property string m_rankPM25_24h;
    property string m_rankPM10_24h;

    PM25 {
        id: api
    }

    PlasmaComponents.TabBar {
        id: tabBar
        anchors { left: parent.left; right: parent.right }

        PlasmaComponents.TabButton {
            text: i18n("Summary")
            tab: summaryTab
        }

        PlasmaComponents.TabButton {
            text: i18n("Details")
            tab: detailsTab
        }

        PlasmaComponents.TabButton {
            text: i18n("Rank")
            tab: rankTab
        }
    }

    PlasmaComponents.TabGroup {
        id: tabGroup
        anchors { top: tabBar.bottom; bottom:  parent.bottom; left: parent.left; right: parent.right }

        PlasmaComponents.Page {
            id: summaryTab
            clip: true

            Rectangle {
                id: base
                anchors { top: parent.top; topMargin: 4; bottom: pm25.bottom; left: parent.left; right: parent.right }
                color: theme.backgroundColor
                opacity: m_cityname == "" ? 0 : 0.4
            }

            PlasmaComponents.Label {
                id: avgAQI
                anchors { top: parent.top; left: parent.left; leftMargin: 4 }
                font.pointSize: 56//TODO: Make it parent-size dependent
                font.weight: Font.Bold
                font.family: m_customFont ? m_fontFamily : theme.defaultFont.family
                verticalAlignment: Text.AlignTop
                text: m_avgAQI
                color: changeColor()
            }

            PlasmaComponents.Label {
                id: cityName
                anchors { top: parent.top; topMargin: 15; left: avgAQI.right; right: parent.right; rightMargin: 4 }
                font.pointSize: 1.8 * theme.defaultFont.pointSize
                font.weight: Font.DemiBold
                font.family: m_customFont ? m_fontFamily : theme.defaultFont.family
                horizontalAlignment: Text.AlignRight
                clip: true//city's name could be too long to display
                text: m_cityname
            }

            PlasmaComponents.Label {
                id: quality
                anchors { top: cityName.bottom; right: cityName.right; bottom: avgAQI.bottom; bottomMargin: 15 }
                font.pointSize: 1.1 * theme.defaultFont.pointSize
                font.family: m_customFont ? m_fontFamily : theme.defaultFont.family
                horizontalAlignment: Text.AlignRight
                verticalAlignment: Text.AlignBottom
                text: m_avgQuality
                color: changeColor()
            }

            PlasmaComponents.Label {
                id: timepoint
                anchors { top: quality.bottom; left: avgAQI.right; right: cityName.right }
                font.weight: Font.Light
                font.pointSize: theme.smallestFont.pointSize
                font.family: m_customFont ? m_fontFamily : theme.defaultFont.family
                horizontalAlignment: Text.AlignRight
                text: m_timePoint.slice(0, 10) + " " + m_timePoint.slice(-9, -4)
                elide: Text.ElideLeft//the left is year-month-day, it could be ignored if necessary.
            }

            PlasmaComponents.Label {
                id: pollutant
                anchors { top: timepoint.bottom; left: avgAQI.left }
                font.family: m_customFont ? m_fontFamily : theme.defaultFont.family
                text: m_avgPollutant != "" ? i18n("Primary Pollutant:") + " " + m_avgPollutant : ""
            }

            PlasmaComponents.Label {
                id: pm25
                anchors { top: m_avgPollutant == "" ? timepoint.bottom : pollutant.bottom; left: avgAQI.left }
                font.family: m_customFont ? m_fontFamily : theme.defaultFont.family
                text: m_avgpm25 != "" ? "PM2.5: " + m_avgpm25 + " μg/m<sup>3</sup>" : ""
            }

            PlasmaComponents.Label {
                id: poweredBy
                anchors { top: pm25.bottom; bottom: parent.bottom; right:parent.right }
                font.underline: true
                font.pointSize: theme.smallestFont.pointSize
                font.weight: Font.Light
                font.family: m_customFont ? m_fontFamily : theme.defaultFont.family
                verticalAlignment: Text.AlignBottom
                text: m_cityname == "" ? "" : i18n("Powered By PM25.in")
            }

            PlasmaComponents.Label {
                anchors { left: parent.left; right: parent.right }
                font.family: m_customFont ? m_fontFamily : theme.defaultFont.family
                wrapMode: Text.WordWrap
                visible: error == "" ? false : true
                text: error
            }
        }

        PlasmaComponents.Page {
            id: detailsTab

            PlasmaComponents.Label {
                id: unitBar
                anchors { left: parent.left; right: parent.right }
                clip: true
                font.family: m_customFont ? m_fontFamily : theme.defaultFont.family
                text: m_cityname != "" ? i18n("Unit:") + " μg/m<sup>3</sup> (" + i18n("CO:") + " mg/m<sup>3</sup>)" : ""
            }

            Flickable {
                id: dataView
                contentWidth: psedoTable.width
                contentHeight: psedoTable.height
                interactive: false//disable drag

                Row {
                    id: psedoTable
                    spacing: 6

                    PlasmaComponents.Label {
                        font.family: m_customFont ? m_fontFamily : theme.defaultFont.family
                        text: m_cityname != "" ? "<b>" + i18n("Station") + "</b><br />" + m_stations : ""
                    }

                    PlasmaComponents.Label {
                        font.family: m_customFont ? m_fontFamily : theme.defaultFont.family
                        text: m_cityname != "" ? "<b>AQI</b><br />" + m_aqis : ""
                        horizontalAlignment: Text.AlignRight
                    }

                    PlasmaComponents.Label {
                        font.family: m_customFont ? m_fontFamily : theme.defaultFont.family
                        text: m_cityname != "" ? "<b>" + i18n("Quality") + "</b><br />" + m_qualitys : ""
                        horizontalAlignment: Text.AlignRight
                    }

                    PlasmaComponents.Label {
                        font.family: m_customFont ? m_fontFamily : theme.defaultFont.family
                        text: m_cityname != "" ? "<b>" + i18n("Primary Pollutant") + "</b><br />" + m_ppollutants : ""
                        horizontalAlignment: Text.AlignRight
                    }

                    PlasmaComponents.Label {
                        font.family: m_customFont ? m_fontFamily : theme.defaultFont.family
                        text: m_cityname != "" ? "<b>PM2.5</b><br />" + m_pm2_5s : ""
                        horizontalAlignment: Text.AlignRight
                    }

                    PlasmaComponents.Label {
                        font.family: m_customFont ? m_fontFamily : theme.defaultFont.family
                        text: m_cityname != "" ? "<b>PM10</b><br />" + m_pm10s : ""
                        horizontalAlignment: Text.AlignRight
                    }

                    PlasmaComponents.Label {
                        font.family: m_customFont ? m_fontFamily : theme.defaultFont.family
                        text: m_cityname != "" ? "<b>" + i18n("CO") + "</b><br />" + m_cos : ""
                        horizontalAlignment: Text.AlignRight
                    }

                    PlasmaComponents.Label {
                        font.family: m_customFont ? m_fontFamily : theme.defaultFont.family
                        text: m_cityname != "" ? "<b>" + i18n("NO<sub>2</sub>") + "</b><br />" + m_no2s : ""
                        horizontalAlignment: Text.AlignRight
                    }

                    PlasmaComponents.Label {
                        font.family: m_customFont ? m_fontFamily : theme.defaultFont.family
                        text: m_cityname != "" ? "<b>" + i18n("SO<sub>2</sub>") + "</b><br />" + m_so2s : ""
                        horizontalAlignment: Text.AlignRight
                    }

                    PlasmaComponents.Label {
                        font.family: m_customFont ? m_fontFamily : theme.defaultFont.family
                        text: m_cityname != "" ? "<b>" + i18n("O<sub>3</sub>/8h") + "</b><br />" + m_o38hs : ""
                        horizontalAlignment: Text.AlignRight
                    }
                }
            }

            PlasmaExtras.ScrollArea {
                anchors { top: unitBar.bottom; bottom: parent.bottom; left: parent.left; right: parent.right }
                flickableItem: dataView
            }
        }

        PlasmaComponents.Page {
            id: rankTab//Only quering city, along with top and last 10 cities.

            Flickable {
                id: rankView
                contentWidth: rankTable.width
                contentHeight: rankTable.height
                interactive: false//disable drag

                Row {//TODO: Add co_24h, no2_24h, o3_24h, so2_24h.
                    id: rankTable
                    spacing: 6

                    PlasmaComponents.Label {
                        text: m_rankNum != "" ? "<b>" + i18n("Rank") + "</b><br />" + m_rankNum : ""
                        horizontalAlignment: Text.AlignRight
                    }

                    PlasmaComponents.Label {
                        text: m_rankCities != "" ? "<b>" + i18n("City") + "</b><br />" + m_rankCities : ""
                        horizontalAlignment: Text.AlignRight
                    }

                    PlasmaComponents.Label {
                        text: m_rankAQIs != "" ? "<b>AQI</b><br />" + m_rankAQIs : ""
                        horizontalAlignment: Text.AlignRight
                    }

                    PlasmaComponents.Label {
                        text: m_rankQuality != "" ? "<b>" + i18n("Quality") + "</b><br />" + m_rankQuality : ""
                        horizontalAlignment: Text.AlignRight
                    }

                    PlasmaComponents.Label {
                        text: m_rankLevel != "" ? "<b>" + i18n("Level") + "</b><br />" + m_rankLevel : ""
                        horizontalAlignment: Text.AlignRight
                    }

                    PlasmaComponents.Label {
                        text: m_rankPPollutants != "" ? "<b>" + i18n("Primary Pollutant") + "</b><br />" + m_rankPPollutants : ""
                        horizontalAlignment: Text.AlignRight
                    }
                    
                    PlasmaComponents.Label {
                        text: m_rankPM25_24h != "" ? "<b>PM2.5/24h</b><br />" + m_rankPM25_24h : ""
                        horizontalAlignment: Text.AlignRight
                    }
                    
                    PlasmaComponents.Label {
                        text: m_rankPM10_24h != "" ? "<b>PM10/24h</b><br />" + m_rankPM10_24h : ""
                        horizontalAlignment: Text.AlignRight
                    }
                }
            }

            PlasmaExtras.ScrollArea {
                anchors.fill: parent
                flickableItem: rankView
            }
        }
    }

    Timer {
        id: timer
        interval: m_interval * 3600000 //1h=3600000ms
        running: false
        repeat: true
        onTriggered: api.query(m_city)
    }

    Timer {
        id: rankTimer
        interval: 43200000 //12 hours
        running: true
        repeat: true
        onTriggered: api.rank()
    }

    function changeColor() {
        if (m_avgAQI <= 100)
            return theme.viewFocusColor
        else    if (m_avgAQI <= 200)
            return theme.linkColor
        else    if (m_avgAQI <= 300)
            return "#8F" + theme.viewFocusColor.toString().slice(3)
        else
            return theme.visitedLinkColor
    }

    function configChanged() {
        timer.running = false;

        m_city = plasmoid.readConfig('city');
        m_interval = plasmoid.readConfig('interval');
        m_customFont = plasmoid.readConfig('customFont');
        m_fontFamily = plasmoid.readConfig('fontFamily');

        timer.running = true;
        api.query(m_city)

        if (m_rankNum == "")//get rank at the beginning
            api.rank()
    }

    function updateToolTip() {
        var toolTip = new Object;
        toolTip['image'] = 'weather-many-clouds';//TODO a new icon
        toolTip['mainText'] = i18n('AQI China');
        toolTip['subText'] = m_cityname != "" ? m_cityname + ": " + m_avgQuality : "";
        plasmoid.popupIconToolTip = toolTip;
    }

    Component.onCompleted: {
        plasmoid.popupIcon = 'weather-many-clouds';//TODO a new icon as well
        plasmoid.aspectRatioMode = IgnoreAspectRatio;
        plasmoid.addEventListener('configChanged', mainWindow.configChanged);
        updateToolTip();
    }
}